from django.utils.deprecation import MiddlewareMixin
from django.db.models import Q
from logzero import logger
from django.shortcuts import render
from service.models import Teacher, Student, Administrator

TChoice = ['choice_show_file', 'choice_show_generation', 'show_all_choice', 'stu_choice_answer', 'stu_choice_wrong']
TCompletion = ['file_completion_generation', 'show_completion_homepage', 'show_all_completion', 'question_save', 'stu_completion_answer', 'stu_completion_wrong']
Tservice = ['operate_login', 'register', 'operate_register', 'operate_logout', 'modify', 'myhome', 'classadd', 'classdel', 'classJoin', 'stu_submit', 'account_show', 'account_del', 'log_show', 'classExit']
TShortAnswer = ['file_generation', 'show_homepage', 'show_all_shortAnswer', 'stu_shortAnswer_answer', 'stu_shortAnswer_wrong', 'question_save']


Tapp_map = {'choice': TChoice, 'completion': TCompletion, 'service': Tservice, 'shortAnswer': TShortAnswer}


class AuthMiddleware(MiddlewareMixin):
    def process_request(self, request):
        path = request.path_info
        url = path.split('/')
        if len(url) == 0 or len(url) == 1 or len(url) == 2:  # 过滤杂项
            return None
        app = url[1]
        need_login = url[2]
        if app == 'media' or app == 'login' or app == 'register' or need_login == 'operate_logout':
            return None
        if app == 'service':  # 针对 showcode 做单独处理
            if need_login == 'showcode' or need_login == 'operate_login' or need_login == 'operate_register' or need_login == 'register':
                return None
        account = request.session.get('account')
        iden = request.session.get('iden')
        if iden:
            if app in Tapp_map:
                if need_login in Tapp_map[app]:
                    # if need_login == 'register' and iden != 'manager':  # process_request 不能直接有返回值 若要 return 必须加条件语句
                    #     return render(request, 'error.html', {'message': '对不起，你没有管理员权限，请联系管理员'})
                    if account is None:                                      #若没登录   或 被人挤掉
                        logger.info("你已退出登录状态，请重新登陆")
                        return render(request, 'error.html', {'message': '你已退出登录状态，请重新登陆'})
                    else:
                        if iden == 'teacher':
                            filename = Teacher
                        elif iden == 'student':
                            filename = Student
                        else:
                            filename = Administrator
                        try:
                            user_account = filename.objects.get(Q(Account=account))
                        except:
                            logger.info("非法session")
                            request.session.flush()
                            return render(request, 'error.html', {'message': '非法访问，请登录'})
                        #    return HttpResponseRedirect('/service/login/')    #清空session 跳转登录界面
                        if user_account:
                            return None
        else:
            logger.info("非法访问")
            return render(request, 'error.html', {'message': '对不起，请注册账号'})

